﻿using OpenTK.Graphics.OpenGL;

namespace OpenGl.Explore.FirstApp
{
    public class VertexBuffer : OpenglObject, IBindable
    {
        public VertexBuffer()
        {
            GL.GenBuffers(1, out _id);
        }

        public void Bind()
        {
            GL.BindBuffer(BufferTarget.ArrayBuffer, _id);
        }

        public void SetData<T>(T[] data, int itemSize, BufferUsageHint usage, params int[] attrib) where T : struct
        {
            GL.BufferData(BufferTarget.ArrayBuffer, itemSize * data.Length, data, usage);
            var stride = attrib.Sum(i => i * sizeof(float));
            var offset = 0;
            for (var i = 0; i < attrib.Length; i++)
            {
                if (i > 0)
                    offset += attrib[i - 1] * sizeof(float);
                GL.VertexAttribPointer(i, attrib[i], VertexAttribPointerType.Float, false, stride, new IntPtr(offset));
                GL.EnableVertexAttribArray(i);
            }

        }

        public void SetData(float[] data, int size, BufferUsageHint usage, int index)
        {
            GL.BufferData(BufferTarget.ArrayBuffer, sizeof(float) * data.Length, data, usage);
            GL.VertexAttribPointer(index, size, VertexAttribPointerType.Float, false, size * sizeof(float), new IntPtr(0));
            GL.EnableVertexAttribArray(index);
        }

        public void Unbind()
        {
            GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
        }

        protected override void Destory()
        {
            GL.DeleteBuffers(1, ref _id);
        }
    }
}
